<template>
  <div class="app-container">
    <!--对象搜索树型列表-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用例编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入用例编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用例名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用例名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块名称" prop="module_name">
        <el-input
          v-model="queryParams.module_name"
          placeholder="请输入模块名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用例类型" prop="type">
        <y-select
          v-model="queryParams.type"
          placeholder="请选择用例类型"
          :options="tms_tc_type"
        />
      </el-form-item>
      <el-form-item label="执行结果" prop="status">
        <y-select
          v-model="queryParams.status"
          placeholder="请选择执行结果"
          :options="tms_job_status"
        />
      </el-form-item>
      <el-form-item label="分析结论" prop="analysis">
        <y-select
          v-model="queryParams.analysis"
          placeholder="请选择分析结论"
          :options="tms_tc_analysis"
        />
      </el-form-item>
      <el-form-item label="执行时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--对象操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Back" @click="handleBack"
          >返回</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          @click="handleAnalysis"
          v-hasPermi="['tms:job:start']"
          :disabled="isEmpty(selectedCases)"
          >分析
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="type === '1'">
        <el-button
          type="primary"
          plain
          icon="Refresh"
          @click="handleRetry"
          v-hasPermi="['tms:job:start']"
          :disabled="isEmpty(selected)"
          >重试
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <y-export
          :url="'tms/job/log/export/'"
          :ids="ids"
          :filename="'joblog_data'"
          v-hasPermi="['tms:job:export']"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDelete"
          v-hasPermi="['tms:job:delete']"
          >删除
        </el-button>
      </el-col>
      <y-right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      >
      </y-right-toolbar>
    </el-row>

    <!--对象列表-->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      :data="joblogList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
        reserve-selection
      />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="日志编号"
        width="300"
        align="center"
        prop="id"
        v-if="columns[0].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="用例编号"
        width="300"
        align="center"
        prop="number"
        v-if="columns[1].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="'/tms/testcase-info/index/' + scope.row.testcase"
            class="link-type"
          >
            <span>{{ scope.row.number }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="用例名称"
        width="300"
        align="center"
        key="name"
        prop="name"
        :show-overflow-tooltip="true"
        v-if="columns[2].visible"
        sortable
      />
      <el-table-column
        label="模块名称"
        width="300"
        align="center"
        key="module_name"
        prop="module_name"
        :show-overflow-tooltip="true"
        v-if="columns[3].visible"
        sortable
      />
      <el-table-column
        label="用例级别"
        width="110"
        align="center"
        prop="level"
        v-if="columns[4].visible"
        sortable
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <y-dict-tag :options="tms_tc_level" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column
        label="用例类型"
        width="110"
        align="center"
        prop="type"
        v-if="columns[5].visible"
        :show-overflow-tooltip="true"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_tc_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        label="初始化时间"
        width="160"
        align="center"
        prop="create_time"
        v-if="columns[6].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        width="160"
        align="center"
        prop="run_time"
        v-if="columns[7].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.run_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        width="160"
        align="center"
        prop="finished"
        v-if="columns[8].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.finished) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="执行人"
        width="110"
        align="center"
        prop="executor_name"
        v-if="columns[9].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="执行结果"
        width="110"
        align="center"
        prop="status"
        v-if="columns[10].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_job_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="执行耗时(秒)"
        width="130"
        align="center"
        v-if="columns[11].visible"
        sortable
      >
        <template #default="scope">
          <span v-if="scope.row.status != '0'">{{
            (
              (new Date(scope.row.finished ? scope.row.finished : Date.now()) -
                new Date(
                  scope.row.run_time ? scope.row.run_time : Date.now()
                )) /
              1000
            ).toFixed() + " 秒"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="分析结论"
        width="110"
        align="center"
        v-if="columns[12].visible"
        sortable
      >
        <template #default="scope">
          <div v-if="scope.row.analysis">
            <y-dict-tag
              :options="tms_tc_analysis"
              :value="scope.row.analysis"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        width="200"
        align="center"
        prop="remark"
        v-if="columns[13].visible"
        :show-overflow-tooltip="true"
        sortable
      />
      <el-table-column
        label="分析人"
        width="110"
        align="center"
        prop="analyser_name"
        v-if="columns[14].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" fixed="right" align="center" width="120">
        <template #default="scope">
          <el-tooltip
            v-if="scope.row.job_type === '0'"
            content="手工执行"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="CaretRight"
              @click="handleRun(scope.row)"
              v-hasPermi="['tms:job:start']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="执行结果" placement="top">
            <el-button
              link
              type="primary"
              icon="ChatLineSquare"
              @click="handleHistory(scope.row)"
              v-hasPermi="['tms:job:log']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.job_type === '1'"
            content="执行日志"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="ChatDotSquare"
              @click="handleJobLog(scope.row)"
              v-hasPermi="['tms:job:log']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['tms:job:delete']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--列表分页-->
    <y-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      @pagination="getList"
    />

    <!-- 用例执行对话框 -->
    <manual
      :id="id"
      v-model="openManual"
      :title="title"
      :updateJob="updateJob"
      :getJobLog="getJobLog"
      :listJobLog="listJobLog"
      :updateJobLog="updateJobLog"
      :updateExecutionJob="updateExecutionJob"
      @submited="submited"
      @close="openManual = false"
    >
    </manual>

    <!-- 用例执行历史对话框 -->
    <history
      :id="id"
      v-model="openHistory"
      :title="title"
      :listJobLog="listJobLog"
      @close="openHistory = false"
    >
    </history>

    <!-- 用例分析对话框 -->
    <analysis
      :data="selectedCases"
      v-model="openAnalysis"
      :title="title"
      :level="level"
      :updateJobLog="updateJobLog"
      @submited="submited"
      @close="openAnalysis = false"
    >
    </analysis>

    <!-- 用例重执行对话框 -->
    <retry
      :data="selectedSteps"
      v-model="openRetry"
      :title="title"
      :level="level"
      :updateJobLog="updateJobLog"
      @submited="submited"
      @close="openRetry = false"
    >
    </retry>

    <!-- 用例日志详情展示 -->
    <el-dialog
      title="执行日志"
      v-model="openLog"
      width="1000px"
      @close="openLog = false"
      append-to-body
    >
      <el-form :model="form" label-width="100px">
        <el-input
          :rows="15"
          readonly="readonly"
          prop="detail"
          label-width="100px"
          v-model="form.detail"
          type="textarea"
        />
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="JobLog">
import { isEmpty } from "@/utils/validate";
import { getJob, updateJob } from "@/api/tms/job";
import { updateExecutionJob } from "@/api/tms/job/execution";
import {
  getJobLog,
  listJobLog,
  delJobLog,
  updateJobLog,
} from "@/api/tms/job/log";
import Manual from "./components/Manual";
import History from "./components/History";
import Analysis from "./components/Analysis";
import Retry from "./components/Retry";

const route = useRoute();
const { proxy } = getCurrentInstance();
const { tms_job_status, tms_tc_type, tms_tc_level, tms_tc_analysis } =
  proxy.useDict(
    "tms_job_status",
    "tms_tc_type",
    "tms_tc_level",
    "tms_tc_analysis"
  );

const id = ref(null);
const ids = ref([]);
const title = ref("");
const total = ref(0);
const type = ref("0");
const level = ref("0");
const loading = ref(true);
const multiple = ref(true);
const joblogList = ref([]);
const showSearch = ref(false);
const dateRange = ref([]);
const selected = ref([]);
const selectedSteps = ref([]);
const selectedCases = ref([]);
const openLog = ref(false);
const openManual = ref(false);
const openHistory = ref(false);
const openAnalysis = ref(false);
const openRetry = ref(false);

// 列显隐信息
const columns = ref([
  { key: 0, label: `日志编号`, visible: false },
  { key: 1, label: `用例编号`, visible: true },
  { key: 2, label: `模块编号`, visible: true },
  { key: 3, label: `用例名称`, visible: true },
  { key: 4, label: `优先级`, visible: true },
  { key: 5, label: `用例类型`, visible: true },
  { key: 6, label: `初始化时间`, visible: false },
  { key: 7, label: `开始时间`, visible: true },
  { key: 8, label: `结束时间`, visible: true },
  { key: 9, label: `执行人`, visible: true },
  { key: 10, label: `执行结果`, visible: true },
  { key: 11, label: `执行耗时`, visible: true },
  { key: 12, label: `分析结论`, visible: true },
  { key: 13, label: `备注`, visible: true },
  { key: 14, label: `分析人`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    job: route.query.job,
    job_execution: route.query.job_execution,
    testcase: route.query.testcase,
    number: undefined,
    type: undefined,
    status: undefined,
    page: 1,
    limit: 10,
  },
});

const { queryParams, form } = toRefs(data);

/** 查询执行日志列表 */
async function getList() {
  loading.value = true;
  Promise.all([
    getJob(queryParams.value.job),
    listJobLog(queryParams.value, dateRange.value),
  ])
    .then(([jobResponse, jobLogResponse]) => {
      type.value = jobResponse.data.type;
      level.value = jobResponse.data.level;
      joblogList.value = jobLogResponse.data;
      total.value = jobLogResponse.total;
    })
    .catch((error) => {
      console.error("获取信息失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 返回操作 */
function handleBack() {
  proxy.$router.back();
}

/** 搜索操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/**多选框选中数据操作 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
  selected.value = selection.map((item) => item);
  selectedSteps.value = formatCaseData(selected.value);
  selectedCases.value = selection.filter(
    (item) => item.status !== "3" && item.status !== "0"
  );
}

/**执行用例操作 */
function handleRun(row) {
  id.value = row.id;
  openManual.value = true;
  title.value = "手工执行";
}

/**分析用例操作 */
function handleAnalysis(row) {
  id.value = row.id;
  openAnalysis.value = true;
  title.value = "结果分析";
}

/**开始重试操作 */
function handleRetry(row) {
  id.value = row.id;
  openRetry.value = true;
  title.value = "重新执行";
}

/**查看用例执行历史操作 */
function handleHistory(row) {
  id.value = row.testcase;
  openHistory.value = true;
  title.value = "历史结果";
}

/** 详细按钮操作 */
function handleJobLog(row) {
  openLog.value = true;
  form.value = row;
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    } else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delJobLog(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection();
    getList();
  } catch (error) {
    console.error(error);
  }
}

/** 格式化用例数据 */
function formatCaseData(data) {
  return data.map((item) => {
    return {
      ...item,
      steps: item.steps.map((step) => {
        return {
          ...step,
          id: item.id + "_" + step.id,
        };
      }),
    };
  });
}

/** 添加/修改对象后触发事件 */
function submited() {
  getList();
}

onMounted(() => {
  getList();
});
</script>
